
// 一、 初始化地图


// ----打开fmap地图start---- //
var fn_map
var open_fmap=function(div_id,map_detail,user){
  console.log(user,'/static/map_data/'+user+'/')
  var content=map_detail.content
  var file=content.split('.')[0]
  fn_map = new fengmap.FMMap({
    //渲染dom
    container: document.getElementById(div_id),
    //地图数据位置
    mapServerURL: '/static/map_data/'+user+'/',
    defaultMapScaleLevel: 19,
    //开发者申请应用下web服务的key
    key: '9ba50831cbdde4f07c79740dae2959ff',
    //开发者申请应用名称
    appName: 'map测试',
   });
  fn_map.openMapById(file);
    // 地图记载完成事件
  fn_map.on('loadComplete', function () {
    searchAnalyser = new fengmap.FMSearchAnalyser(fn_map)
  })
}

// ----打开fmap地图end---- //



// 地图地址搜索功能
var searchAnalyser;
var select_obj;
var search_map=function(self){
  if(select_obj!=null){
    select_obj.selected=false
  }
  addr=self.value.trim();
  // console.log(addr)
  if(addr==''){
    layer.msg('请输入地址')
    return
  }

  var searchRequest = new fengmap.FMSearchRequest();
  searchRequest.keyword = addr;
  searchRequest.nodeType = fengmap.FMNodeType.MODEL;
  searchRequest.groupID =1

  var sortRes = searchAnalyser.getQueryResult(searchRequest, ['SINGLE']);

  $('#addr_list').empty()
  for(var i=0;i<sortRes.length;i++){
    if(addr!=sortRes[i].name){
      var opt='<option>'+sortRes[i].name+'</option>'
      $('#addr_list').append(opt)
    }else{
      // console.log(sortRes[i],sortRes[i].target.selected)
      sortRes[i].target.selected=true
      select_obj=sortRes[i].target
      fn_map.moveTo(sortRes[i].mapCoord)
    }
  }
  // $('#search_address').click()
  return sortRes;
}

//查询周边信息
var trakcer_addr_obj={}
search_by_xy=function(device_id,x,y,gid=1){
  // console.log('diatan')
  var searchRequest = new fengmap.FMSearchRequest();
  // var cacu=new fengmap.FMCalculator()

  searchRequest.groupID = gid;
  searchRequest.circle = {
      //查询范围中心点坐标
      center:{
          x: x,
          y: y
      },
      radius: 50  //查询范围半径
  };
  var sortRes = searchAnalyser.getQueryResult(searchRequest, ['SINGLE', 'CIRCLE']);
  // console.log(sortRes)
  for(var i=0;i<sortRes.length;i++){
    // console.log(sortRes[i].name)
    if(sortRes[i].name!=null){
      var start=sortRes[i].mapCoord
      var end={'x':x,'y':y}
      // var distance=new fengmap.FMCalculator.GetLength(start, end)
      // console.log(distance,'1')
      var distance=fengmap.FMCalculator.GetLength(start, end)
      distance=distance.toFixed()
      // console.log(distance,'2')
      trakcer_addr_obj[device_id]=sortRes[i].name+'附近'+distance.toString()+'米'
      return sortRes[i].name+'附近'+distance.toString()+'米'
    }
  }
}





var tracker_layer
var tracker_name_layer
var tracker_marker_obj={}
var tracker_marker_name_obj={}

var add_tracker_marker=function(obj){
  // console.log(obj)
  var user_name=obj.user_name
  var icon_show='/static/show_icon/'+obj.user_detail.icon+'.png'
  var lng=parseFloat(obj.dynamic.lng);
  var lat=parseFloat(obj.dynamic.lat);
  // console.log(icon_show,lng,lat,user_name)
  //返回当前层中第一个imageMarkerLayer,如果没有，则自动创建
  tracker_layer = group.getOrCreateLayer('imageMarker');
  var tracker = new fengmap.FMImageMarker({
    //设置图片路径
    url: icon_show,
    name: user_name,
    x: lng,
    y: lat,
    size: 25,
    callback: function () {
      // 在图片载入完成后，设置 "一直可见"
      tracker.alwaysShow();
    }
  });
  tracker['user_name']=user_name
  tracker['device_id']=obj.device_id
  tracker['tracker']=obj

  tracker_layer.addMarker(tracker);
  search_by_xy(obj.device_id,lng,lat)
  tracker_marker_inforwindow(tracker,obj)

  // 标识文字marker
  var text_x=lng;
  var text_y=lat+10;
  // console.log(text_x,text_y)
  tracker_name_layer = group.getOrCreateLayer('textMarker');
  tracker_name = new fengmap.FMTextMarker({
    x: text_x,
    y: text_y,
    ID: obj.device_id,
    name:user_name,
    //填充色
    fillcolor: "255,0,0",
    //字体大小
    fontsize: 15,
    //边框色
    strokecolor: "255,255,0",
    callback: function () {
      // 在图片载入完成后，设置 "一直可见"
      tracker_name.alwaysShow();
    }
  });
  //文本标注层添加文本Marker
  tracker_name['device_id']=obj.device_id
  tracker_name_layer.addMarker(tracker_name);
  tracker_marker_obj[obj.device_id]=tracker
  tracker_marker_name_obj[obj.device_id]=tracker_name
  if(lng!=0 && lat!=0){
    fn_map.moveTo({x:text_x,y:text_y,time:0.3})
  }
  return {'img':tracker,'text':tracker_name}
}


// 添加静态覆盖物，建筑，基站等
var static_marker_layer
var static_marker_name_layer
var static_marker_obj={};
var static_marker_name_obj={};

var add_static_marker=function(obj,kind){
  // console.log(obj)
  var unique='device_id'
  var num;
  if(obj.device_id==null){
    unique='name'
    num=obj.asset
  }else{
    num=obj.scann_data
  }
  if(num!=='0'){
    num=eval('('+num+')').length.toString()
  }

  var icon_dict={'building':'/static/show_icon/normal.png','camera':'/static/show_icon/camera.png','scanner':'/static/show_icon/scanner.png','tag':'/static/show_icon/person/green_man.png'}
  var icon_show=icon_dict[kind]

  var icon;
  icon=eval("("+obj.param_set+")")
  icon=icon.icon
  if (icon!=null){
    icon_show='/static/show_icon/'+icon+'.png'
  }
  var posi=[0,0]
  if(obj['position']!='0' && obj['position']!=null){
    posi=eval('('+obj['position']+')').location
    posi=posi.split(',')  
  }

  //返回当前层中第一个imageMarkerLayer,如果没有，则自动创建
  static_marker_layer = group.getOrCreateLayer('imageMarker');
  var static_marker = new fengmap.FMImageMarker({
    //设置图片路径
    url: icon_show,
    name: obj[unique],
    x: posi[0],
    y: posi[1],
    size: 35,
    callback: function () {
      // 在图片载入完成后，设置 "一直可见"
      static_marker.alwaysShow();
    }
  });
  static_marker['overlay_name']=obj[unique]
  static_marker['overlay_kind']=kind
  static_marker['overlay']=obj

  static_marker_layer.addMarker(static_marker);
  static_marker_obj[obj[unique]]=static_marker

  var text_x=parseFloat(posi[0]);
  var text_y=parseFloat(posi[1])+10;

  
  // console.log(num)
  var title=obj[unique]+'('+num+')'
  static_marker_name_layer = group.getOrCreateLayer('textMarker');
  var textMarker = new fengmap.FMTextMarker({
    x: text_x,
    y: text_y,
    ID: obj[unique],
    name:title,
    //填充色
    fillcolor: "255,0,0",
    //字体大小
    fontsize: 20,
    //边框色
    strokecolor: "255,255,0",
    callback: function () {
      // 在图片载入完成后，设置 "一直可见"
      textMarker.alwaysShow();
    }
  });
  //文本标注层添加文本Marker
  textMarker['textMarker_id']=obj[unique]
  textMarker['overlay_kind']=kind
  static_marker_name_layer.addMarker(textMarker);
  static_marker_name_obj[obj[unique]]=textMarker
  fn_map.moveTo({x:text_x,y:text_y,time:0.3})
  return {'img':static_marker,'text':textMarker}
}

// ----添加marker函数 end----- //

// 删除tracker图标
var remove_tracker_marker=function(device_id){

  // 要把信息弹窗先关掉，不然报错
  if(trakcer_marker_infowindow_obj[device_id]!=null){
    trakcer_marker_infowindow_obj[device_id].close()
  }
  tracker_layer.removeMarker(tracker_marker_obj[device_id])
  delete tracker_marker_obj[device_id]

  tracker_name_layer.removeMarker(tracker_marker_name_obj[device_id])
  delete tracker_marker_name_obj[device_id]

}

// 隐藏/展示tracker图标
var hide_tracker_marker=function(device_id,value){
  if(trakcer_marker_infowindow_obj[device_id]!=null && value==false){
    trakcer_marker_infowindow_obj[device_id].close()
  }
  tracker_marker_obj[device_id].show=value
  tracker_marker_name_obj[device_id].show=value
}

// 移动tracker和名称
var move_tracker_marker=function(device_id,x,y){
  tracker_marker_obj[device_id].setPosition(x,y,1,5)
  tracker_marker_obj[device_id].show=true
  tracker_marker_name_obj[device_id].setPosition(x,y+15,1,5)
  tracker_marker_name_obj[device_id].show=true
}

// 删除static图标
var remove_static_marker=function(unique_id){
  if(static_marker_obj[unique_id]!=null){
    static_marker_layer.removeMarker(static_marker_obj[unique_id])
    static_marker_name_layer.removeMarker(static_marker_name_obj[unique_id])
  }
}
// 隐藏/显示固定的marker
var hide_static_marker=function(kind,value){
  // static_marker_obj[unique_id].show=value
  // static_marker_name_obj[unique_id].show=value
  // var objs=static_marker_layer.imageMarkers
  // console.log(static_marker_obj)
  for(var k in static_marker_obj){
    var mark=static_marker_obj[k]
    if(mark.overlay_kind==kind){
      mark.show=value
    }
  }
  for(var k in static_marker_name_obj){
    var mark=static_marker_name_obj[k]
    if(mark.overlay_kind==kind){
      mark.show=value
    }
  }
}



// 获取覆盖物详情
var get_overlay_detail=function(kind,overlay_target){
  
  var overlay=eval(kind)
  // console.log(overlay,kind,overlay_target)
  var detail;
  for (var i = overlay.length - 1; i >= 0; i--) {
    var name;
    if(kind=='building'){
      name=overlay[i]['name']
    }else{
      name=overlay[i]['device_id']
    }
      if(overlay_target==name){
        detail=overlay[i]
      }
  }
  // console.log(detail)
  return detail
}
// ----展示/隐藏marker信息窗 start----- //

var all_static_infordow={}

var static_marker_inforwindow=function(obj){
  // console.log(obj)
  var obj_name=obj.overlay_name
  var obj_kind=obj.overlay_kind
  var table_id=obj_kind+obj_name
  var window_content='<br><table id="'+table_id+'" >' + '</table>';
  var obj_detail=get_overlay_detail(obj_kind,obj_name)
  var ctlOpt = {
      //设置弹框的宽度
      width: 350,
      //设置弹框的高度px
      height: 430,
      //设置弹框的内容，文本或html页面元素
      content: window_content,

      //关闭回调函数
      closeCallBack: function () {
          //信息窗点击关闭操作
          delete all_static_infordow[obj_name]
      }
  };
  //添加弹框到地图上，绑定marker
  // 防止重复弹窗
  if(all_static_infordow[obj_name]!=null){
    all_static_infordow[obj_name].close()
    delete all_static_infordow[obj_name]
  }
  var popMarker = new fengmap.FMPopInfoWindow(fn_map, ctlOpt, obj);
  
  all_static_infordow[obj_name]=popMarker
  var table_data=[]
  var table_cols;
  
  if(obj_kind=='building'){
    // console.log(obj_name)
    var build=building_obj[obj_name]
    var num='0'
    if (build.asset!='0') {
      for(var i=0;i<build.asset.length;i++){
        var tag=get_detail_from_id(device,build.asset[i])
        // tag.serv_receive=$('#get_current_time').text()
        table_data.push(tag)
      }
      num=build.asset.length.toString()
    }

    var param_set=eval('('+obj_detail.param_set+')')
    table_cols=[[{ "title": "建筑名字： " + obj_name+"，权限： " + param_set.auth_in, "colspan": 3 }],
            [{ "title": "人数上限： " + param_set.person_limit + "人"+"，停留时限： " + param_set.time_limit + "分", "colspan": 3 }],
            [{ "title": "建筑明细  " + '(当前:' + num + ')', "colspan": 3 }],
            [{ field: 'user_name', title: '名称' },
            // { field: 'department', title: '归属' },
            {
              field: 'serv_receive', title: '进入时间'//, formatter: function (index, row, value) {
            },
            // {
            //   field: 'stop_time', title: '停留时长', //formatter: function (index, row, value) {
            // },
            { field: 'device_id', title: '设备编号' }]
            ]
  }else if(obj_kind=='scanner'){
    var sc=scanner_obj[obj_name]
    var num='0'
    if(sc.scann_data!='0'){
      var scann_data=eval('('+sc.scann_data+')')
      rt=scann_data.pop()
      scann_data.forEach(item=>{
        item.serv_receive=rt
      })
      num=scann_data.length.toString()
      table_data=scann_data
    }
    table_cols=[[{ "title": "设备名称： " + obj_detail.name,width:10, "colspan":4 }],
                [{ "title": "设备ID： " + obj_detail.device_id, "colspan": 4 }],
                [{ "title": "设备类型： " +  obj_detail.kind, "colspan": 2 },{ "title": "设备状态： " + obj_detail.status , "colspan": 2 }],
                [{ "title": "运行详情:  "+ '(当前:' + num + ')', "colspan": 4 }],
                [{ field: 'device_id', title: '标签编号' },{ field: 'rssi', title: '信号强度' },{field: 'serv_receive', title: '时间'},{field: 'ramark', title: '备注'}]
               ]
  }
  
  if(obj_kind!='camera'){
    table.render({
      elem: '#'+table_id,
      data: table_data,
      id:table_id+'_show',
      height: 360,
      cols: table_cols,
      // limits: [10, 15, 20, 25, 50, 100],
      limit: 10000000,
      // page: true
    });
  }
}

var trakcer_marker_infowindow_obj={}
var tracker_marker_inforwindow=function (marker,dev) {
  // 绑定的用户信息
  // console.log(marker)
  var rssi=dev.dynamic.rssi
  var dev_loca=dev.dynamic.location;
  if(trakcer_addr_obj[dev.device_id]!=null){
    dev_loca=trakcer_addr_obj[dev.device_id]
  }
  var user_detail=dev.user_detail;
  var dev_user_name=dev.user_name;
  var param1=user_detail.customize_title1+'：'+user_detail.customize_value1
  var param2=user_detail.customize_title2+'：'+user_detail.customize_value2
  var param3=user_detail.customize_title3+'：'+user_detail.customize_value3
  var info_window_baidu;
  info_window_baidu="<br>"+
   "<div style='margin:0;padding:0;border-radius:20px'>"+
    "<table class='layui-table' lay-size='sm'  style='font-size:10px;margin:0px 0px 0px 0px;padding:0px 0px 0px 0px;'>"+
    "<tbody>"+
    "<tr>"+
      "<td colspan=2 bgcolor='#009688' style='height:15px'><font color='white'>"+dev_user_name+','+param1+','+param2+','+param3+"</font></td>"+
    "</tr>"+

    "<tr >"+
    "<td colspan=2 bgcolor='#009688' style='height:15px'><font color='white'>"+"设备ID : "+dev.device_id+"</font></td>"+
    "</tr>"+
    "<tr>"+
    "<td colspan=2>"+
    "<div class='layui-row'>"+
    "<div class='layui-col-lg4'>"+dev.status+"</div>"+
    "<div class='layui-col-lg8'>"+
    "<i class='fa fa-battery-full pull-right' style = 'font-size:10px; padding-right: 9px;color: #009688;' > "+dev.battery+"</i>"+
    "<i class='fa fa-broadcast-tower pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+rssi+"</i>"+
    "</div>"+
    "</div>"+
    "</td>"+
    "<tr>"+
    "<td colspan=2>"+" <i class='layui-icon layui-icon-console' aria-hidden='true' style='color:#1E9FFF'></i>："+dev.serv_receive+"</td>"+
    "</tr>"+
    "<tr>"+
    "<td colspan=2>"+" <i class='fa fa-map-marker' aria-hidden='true' style='color:#5FB878'></i>："+dev.dynamic.track_type+"</td>"+
    "</tr>"+
    "<tr>"+
    "<td colspan=2>"+"<i class='fa fa-map' aria-hidden='true' style='color:#009688'></i>："+dev_loca+"</td>"+
    "</tr>"+

      "</tbody>"+
  "</table>"+ 
    "<br>"+
    "<button class='layui-btn layui-btn-xs' onclick='turn_to_page(\"fmap_trail\")'>"+
      '<i class="layui-icon ">&#xe715;</i>'+
      "轨迹"+
    "</button>"+
    "<button class='layui-btn layui-btn-xs ' onclick='set_param("+dev.device_id+")'>"+
      '<i class="layui-icon ">&#xe667;</i>'+
      "报警设置"+
    "</button>"+
    // "<button class='layui-btn layui-btn-xs' onclick='command_modal("+dev.device_id+","+g_status+")'>"+
    //   '<i class="layui-icon ">&#xe601;</i>'+
    //   "命令"+
    // "</button>"+
    // "<button class='layui-btn layui-btn-xs' onclick='device_set_modal("+dev.device_id+")'>"+
    //   '<i class="layui-icon ">&#xe614;</i>'+
    //   "设置"+
    // "</button>"+
    // "<button class='layui-btn layui-btn-xs' onclick='turn_to_page(\"interact\")'>"+
    //   '<i class="layui-icon ">&#xe64c;</i>'+
    //   "互动"+
    // "</button>"+
  "</div>"
  ;
  if (marker) {
      //添加绑定marker信息窗
      var ctlOpt = {
          //设置弹框的宽度
          width: 250,
          //设置弹框的高度px
          height: 280,
          //设置弹框的内容，文本或html页面元素
          content: info_window_baidu,

          //关闭回调函数
          closeCallBack: function () {
              //信息窗点击关闭操作
              delete trakcer_marker_infowindow_obj[dev.device_id]
          }
      };
      //添加弹框到地图上，绑定marker
      // 防止重复弹窗
      if(trakcer_marker_infowindow_obj[dev.device_id]!=null){
        trakcer_marker_infowindow_obj[dev.device_id].close()
        delete trakcer_marker_infowindow_obj[dev.device_id]
      }
      var popMarker = new fengmap.FMPopInfoWindow(fn_map, ctlOpt, marker);
      trakcer_marker_infowindow_obj[dev.device_id]=popMarker
      //popMarker.close(); 关闭信息窗
  }
}
// ----展示/隐藏marker信息窗 end----- //